﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.IO;
using Photography.App_Data;

namespace Photography
{
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsErrorPage)
                return;

            if (IsWebsiteUnderMaintenance)
                Response.Redirect("~/maintenance.htm");

            if (!IsPostBack)
                log4net.LogManager.GetLogger(this.GetType()).InfoFormat("User at IP# {0} is visiting page '{1}'", Request.UserHostAddress, Request.Url);
        }

        protected bool IsErrorPage { get { return Path.GetFileName(Request.FilePath).Equals("Error.aspx", StringComparison.InvariantCultureIgnoreCase); } }

        protected bool IsMainPage { get { return Path.GetFileName(Request.FilePath).Equals("Default.aspx", StringComparison.InvariantCultureIgnoreCase); } }

        protected bool IsWebsiteUnderMaintenance
        {
            get
            {
                if (!WebConfigurationManager.AppSettings["maintenance"].Equals("true", StringComparison.InvariantCultureIgnoreCase))
                    return false;

                if (!string.IsNullOrWhiteSpace(Request.QueryString["testing"]))
                    Session["testing"] = Request.QueryString["testing"] == "1";

                return Session["testing"] == null || !(Session["testing"] is bool) ? true : !(bool)Session["testing"];
            }
        }

        public int CurrentCategoryId
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(Request.QueryString["cat"]))
                    foreach (GetCategoriesResult category in Categories.Values)
                        if (Request.QueryString["cat"].Equals(category.Name, StringComparison.InvariantCultureIgnoreCase))
                            return category.ID;

                return 0;
            }
        }

        public Dictionary<int, GetCategoriesResult> Categories
        {
            get
            {
                if (Application["Categories"] == null)
                {
                    Dictionary<int, GetCategoriesResult> categories = new Dictionary<int, GetCategoriesResult>();
                    PhotographyDataContext dataContext = new PhotographyDataContext();
                    foreach (GetCategoriesResult result in dataContext.GetCategories())
                        categories[result.ID] = result;
                    Application["Categories"] = categories;
                }

                return (Dictionary<int, GetCategoriesResult>)Application["Categories"];
            }
        }
    }
}
